package mapred.maxAndMin.way2;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * 自定义了一个Hadoop的可序列化的类，实现的是WritableComparable接口，因为我们需要对Key做比较
 * 如果可序列化类是做Key用，必须实现Comparable接口
 */
public class MaxAndMinValue implements WritableComparable<MaxAndMinValue> {
    private LongWritable min;
    private LongWritable max;
    private IntWritable total;

    // L19-L30：当前类的构造函数
    public MaxAndMinValue() {
        this.min = new LongWritable(0);
        this.max = new LongWritable(0);
        this.total = new IntWritable(0);
    }

    public MaxAndMinValue(long min, long max, int total) {
        this.min = new LongWritable(min);
        this.max = new LongWritable(max);
        this.total = new IntWritable(total);
    }

    // 实现Witable接口，必须要实现write和readFields方法
    @Override
    public void write(DataOutput out) throws IOException {
        // TODO Auto-generated method stub

        // 读取和写入的顺序必须保持一致
        // 下面的2中赋值方式是等价的
        min.write(out);
//        out.writeLong(min.get());
        max.write(out);
//        out.writeLong(max.get());
        total.write(out);
//        out.writeInt(total.get());
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        // TODO Auto-generated method stub
        min.readFields(in);
//        this.min.set(in.readLong());
        max.readFields(in);
//        this.max.set(in.readLong());
        total.readFields(in);
//        this.total.set(in.readInt());
    }

    // 用来在Reducer输出的时候，将我们自定义的这个对象的内部信息输出到文件中
    // Reducer的输出会自动调用当前对象的toString方法
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return min.get() + "\t" + max.get() + "\t" + total.get();
    }

    // L61-L79:标准的java实体类的构造
    public LongWritable getMin() {
        return min;
    }

    public void setMin(LongWritable min) {
        this.min = min;
    }

    public LongWritable getMax() {
        return max;
    }

    public void setMax(LongWritable max) {
        this.max = max;
    }

    public IntWritable getTotal() {
        return total;
    }

    public void setTotal(IntWritable total) {
        this.total = total;
    }

    // 实现Comparable接口，必须要实现compareTo方法
    @Override
    public int compareTo(MaxAndMinValue o) {
        // 形参o，是当前（this）要比较的对象
        // TODO Auto-generated method stub
        return 0;
    }
}

